#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;


int encode(int value, char* buffer, int& len) {
  int bit_value = 0;
  int bit_num = 0;

  if (value < 128) {
    bit_num = 1;
    bit_value = 0;
  } else if (value < 16384) {
    bit_num = 2;
    bit_value = 1;
  } else if (value < 2097152) {
    bit_num = 3;
    bit_value = 3;
  } else if (value < 268435456) {
    bit_num = 4;
    bit_value = 7;
  } else {
    std::cerr<<"encode error"<<std::endl;
    return -1;
  }
  
  value <<= bit_num;
  value += bit_value;
  memcpy(buffer + len, (char*)&value, bit_num);
  len += bit_num;

  return 1;
}

int decode(const char* buffer, int& pos) {
  int bit_value = buffer[pos] % 0x10;
  int bit_num = 0;
  int value = 0;

  if ((bit_value & 0x01) == 0) {
    bit_num = 1;
  } else if ((bit_value & 0x2) == 0) {
    bit_num = 2;
  } else if ((bit_value & 0x4) == 0) {
    bit_num = 3;
  } else if ((bit_value & 0x8) == 0) {
    bit_num = 4;
  } else {
    std::cerr<<"decode error"<<std::endl;
    return -1;
  }
  
  memcpy((char*)&value, buffer + pos, bit_num);
  value >>= bit_num;
  pos += bit_num;

  return value;
}


int main()
{
  srand((unsigned int)time(NULL));
  char buffer[1024];
  memset(buffer,0,1024);
  
  int len = 0;
  for (int i = 0; i < 20; ++i) {
    int num = rand() % 3097152;
    cout<<num<<" ";
    encode(num, buffer, len);
  }
  cout<<"\n------------------\n"<<endl;

  int pos = 0;
  while (pos < len) {
    cout<<decode(buffer, pos)<<" ";
  }
  cout<<endl;
  

  return 0;
}

